<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="申请编号" prop="applyCode">
        <el-input v-model="formData.applyCode" placeholder="请输入申请编号" clearable disabled />
      </el-form-item>
      <el-form-item label="申请人" prop="applyUserId">
        <!-- <el-input v-model="formData.applyUserId" placeholder="请输入申请人" clearable /> -->
        <UserSelect
          v-model="formData.applyUserId"
          placeholder="请选择申请人"
          clearable
          filterable
          @change="onChangeUser"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系方式" clearable disabled />
      </el-form-item>
      <el-form-item label="使用期限" prop="useEndTime">
        <el-date-picker
          v-model="formData.useEndTime"
          type="date"
          value-format="x"
          placeholder="选择使用期限"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="使用理由" prop="applyReson">
        <el-input v-model="formData.applyReson" type="textarea" placeholder="请输入使用理由" clearable maxlength="200" show-word-limit />
      </el-form-item>
      <el-form-item label="附件" prop="file">
        <UploadFile
          v-model="formData.file"
          :limit="1"
          :fileType="fileExtsApplyList"
          :file-size="200"
        />
      </el-form-item>
      <el-divider content-position="left">数字资源</el-divider>
      <el-form-item prop="list" label-width="0">
        <div class="flex items-center justify-end" style="width: 100%;">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <el-table :data="formData.journalApplyDetails" :stripe="true" :show-overflow-tooltip="true">
          <!-- <el-table-column label="主键" align="center" prop="id" /> -->
          <el-table-column label="#" align="center" type="index" width="50" fixed="left" />
          <el-table-column label="封面" align="center" prop="mainImage">
            <template #default="scope">
              <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.mainImage"
                :preview-src-list="[scope.row.mainImage]"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="期刊名称" align="center" prop="journalName" />
          <el-table-column label="期刊编号" align="center" prop="journalCode" />
          <el-table-column label="ISSN/ISBN" align="center" prop="sn" min-width="100px"/>
          <el-table-column label="出版社" align="center" prop="journalFrom" />
          <el-table-column label="语言" align="center" prop="language" />
          <el-table-column label="出版频率" align="center" prop="frequency">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.JOURNAL_FREQUENCY" :value="scope.row.frequency" /> 
            </template>
          </el-table-column>
          <el-table-column label="主题分类" align="center" prop="topicType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.JOURNAL_TYPE" :value="scope.row.topicType" /> 
            </template>
          </el-table-column>
          <el-table-column label="期刊发行时间" align="center" prop="publishYear" />
          <el-table-column label="期刊来源" align="center" prop="source">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.JOURNAL_SOURCE" :value="scope.row.source" />
            </template> 
          </el-table-column>
          <!-- <el-table-column label="订购来源" align="center" prop="orderSource" /> -->
          <!-- <el-table-column
            label="订购日期"
            align="center"
            prop="orderTime"
            :formatter="dateFormatter"
            width="180px"
          /> -->
          <el-table-column
            label="入库时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column
            label="更新时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center" min-width="120px" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openDetail(scope.row)"
                v-hasPermi="['dr:source:query']"
              >
                详情
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm('save')" type="primary" :disabled="formLoading">暂 存</el-button>
      <el-button @click="submitForm('submit')" type="primary" :disabled="formLoading">提 交</el-button>
    </template>

    <!-- 资源详情 -->
    <JournalDetail v-model:visible="detailVisible" :data="currentRow" />
    <!-- 期刊搜索 -->
    <JournalSelectDialog
      v-model:visible="detailSourceSelectVisible"
      v-model="formData.journalApplyDetails"
    />
  </Dialog>
</template>
<script setup lang="ts">
import { fileExtsApplyList, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { JournalVO } from '@/api/dr/journal'
import { JournalApplyApi, JournalApplyVO } from '@/api/dr/journalapply'

/** 期刊申请 表单 */
defineOptions({ name: 'JournalApplyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  applyCode: undefined,
  applyUserId: undefined,
  phone: undefined,
  useEndTime: undefined,
  applyReson: undefined,
  file: undefined,
  journalApplyDetails: []
})
const formRules = reactive({
  applyCode: [
    { required: true, message: '请选择申请人', trigger: ['blur', 'change'] },
  ],
})
const formRef = ref() // 表单 Ref
const detailVisible = ref<boolean>(false)
const currentRow = ref<JournalVO>()
const detailSourceSelectVisible = ref<boolean>(false)

// 新增
const handleAdd = () => {
  detailSourceSelectVisible.value = true
}
const handleDelete = (id: number) => {
  formData.value.journalApplyDetails = formData.value.journalApplyDetails.filter((item: JournalVO) => item.id !== id)
}
// 详情弹窗
const openDetail = (row: any) => {
  currentRow.value = { ...row }
  detailVisible.value = true
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.applyCode = +new Date()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await JournalApplyApi.getJournalApply(id)
      if(type === 'create' && id) {
        delete formData.value.id
      }
      formData.value.journalApplyDetails = formData.value.journalDetails || []
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type?:string) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as JournalApplyVO
    data.operateFlag = type
    data.journalApplyDetails = data.journalApplyDetails?.map((v:any) => ({
      ...v,
      journalId: v.id
    }))
    if (formType.value === 'create') {
      await JournalApplyApi.createJournalApply(data)
      message.success(t('common.createSuccess'))
    } else {
      await JournalApplyApi.updateJournalApply(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    applyCode: undefined,
    applyUserId: undefined,
    phone: undefined,
    useEndTime: undefined,
    applyReson: undefined,
    file: undefined,
    journalApplyDetails: []
  }
  formRef.value?.resetFields()
}
const onChangeUser = (value: any, e:any) => {
  // console.log('onChangeUser', value, e)
  formData.value.phone = e.mobile
}
</script>